﻿namespace Leetcode.N0023.V1;
public class Solution
{
    public ListNode MergeKLists(ListNode[] lists)
    {
        if (lists.Length == 0)
        {
            return null;
        }

        ListNode root = lists[0];
        for (int i = 1; i < lists.Length; i++)
        {
            root = this.Order(root, lists[i]);
        }
        return root;
    }

    private ListNode Order(ListNode node1, ListNode node2)
    {
        if (node1 == null)
        {
            return node2;
        }

        if (node2 == null)
        {
            return node1;
        }

        ListNode node;

        if (node1.val <= node2.val)
        {
            node = node1;
            node.next = this.Order(node1.next, node2);
        }
        else
        {
            node = node2;
            node.next = this.Order(node1, node2.next);
        }

        return node;
    }
}

